<template>
  <el-form ref="ruleFormRef" :rules="rules" :model="dataObj" class="fixed-label-width">
    <el-form-item label="优惠券名称" prop="couponName">
      <el-input v-model="dataObj.couponName" />
    </el-form-item>

    <el-form-item label="优惠券金额" prop="couponValue">
      <el-input v-model="dataObj.couponValue" type="number" />
      <span style="margin-left: 10px; color: #888">(元 / 份)</span>
    </el-form-item>

    <el-form-item label="费用承担方" prop="couponFeeOwner_0">
      <el-radio-group v-model="dataObj.couponFeeOwner_0">
        <el-radio-button label="platform">平台</el-radio-button>
        <el-radio-button label="merchant">商家</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="承担金额" prop="couponFeeOwner_1">
      <el-input v-model="dataObj.couponFeeOwner_1" type="number" />
      <span style="margin-left: 10px; color: #888">(元 / 份)</span>
    </el-form-item>

    <!-- 
  
            couponId
  couponName
  couponValue
  amountPerUser
  expiredAt
  regionIds
  siteIds
  storeIds
  couponFeeOwner
           -->

    <el-form-item label="领取限量" prop="amountPerUser">
      <el-input v-model="dataObj.amountPerUser" onkeyup="this.value=this.value.replace(/[^\d]/g,'') " />
      <span style="margin-left: 10px; color: #888">(每个用户可以领取的张数)</span>
    </el-form-item>
    <el-form-item label="截止有效期" prop="expiredAt">
      <el-date-picker v-model="dataObj.expiredAt" type="datetime" :editable="false" style="width:200px"
        :clearable="false" />
    </el-form-item>

    <el-form-item label="适用区域" >
      <el-select v-model="dataObj.regionIds_list" placeholder="选择区域" 
        multiple collapse-tags style="" >
        <el-option v-for="item in store.state.areaOption" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="areaListStr" type="textarea" readonly />
    </el-form-item>

    <el-form-item label="适用站点" >
      <el-select v-model="dataObj.siteIds_list" placeholder="选择站点" 
        multiple collapse-tags style="width: 240px" >
        <el-option v-for="item in allSiteList" :label="item.siteName" :value="item.siteId" />
      </el-select>
      <el-input v-model="siteListStr" type="textarea" readonly />
    </el-form-item>

    <el-form-item label="适用店铺" >
      <hz-button type="primary" text @click="clickChooseStore">选择</hz-button>
      <el-input v-model="dataObj.storeListStr" type="textarea" readonly />
    </el-form-item>

  </el-form>

  <div class="dialog-footer my-dialog-foot">
    <hz-button type="primary" @click="clickSubmit">确定</hz-button>
    <hz-button @click="clickCancle">取消</hz-button>
  </div>

  <!-- 挑选店铺 -->
  <hz-dialog v-model="addStoreDialog.show" title="选择店铺">
    <choose-store :storeIdList='dataObj.storeIds_list' :dialog="addStoreDialog"
      @updateStoreOkFun="updateStoreOkFun"></choose-store>
  </hz-dialog>
</template>
<script setup>
import { ref, reactive, computed, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { ElMessage } from 'element-plus'
import chooseStore from "@/views/common/chooseStore.vue";

const store = useStore();
const { proxy } = getCurrentInstance();
const ruleFormRef = ref(null);
const props = defineProps({
  formConfig: {
    default: {
      dataObj: {},
      dialog: {},
      type: '',
      okCallback: () => { },
      noCallback: () => { },
    }
  },
  idsToNamesForAll: { type: Function },
  allSiteList: {type: Array},
});

console.log(store.state.areaOption, 88888)
const dataObj = reactive({});   // 编辑的对象
initDataObj();

// 区域文本框显示
const areaListStr = computed(() => {
  let regionIds = dataObj.regionIds_list
  if (!regionIds || !Array.isArray(regionIds)) {
    return '';
  } else if (regionIds[0] == '*' || regionIds.length == store.state.areaOption.length) {
    return '全部'
  } else {
    let str = '';
    regionIds.forEach(id => {
      let obj = store.state.areaOption.find(val => val.id == id)
      if (obj) {
        str += '，' + obj.name
      }
    })
    return str.replace('，', '');
  }
})

// 站点文本框显示
const siteListStr = computed(() => {
  let siteIds = dataObj.siteIds_list
  if (!siteIds || !Array.isArray(siteIds)) {
    return '';
  } else if (siteIds[0] == '*' || siteIds.length == props.allSiteList.length) {
    return '全部'
  } else {
    let str = '';
    siteIds.forEach(siteId => {
      let obj = props.allSiteList.find(val => val.siteId == siteId)
      if (obj) {
        str += '，' + obj.siteName
      }
    })
    return str.replace('，', '');
  }
})

// 店铺弹窗
const addStoreDialog = reactive({
  show: false,
})


// 表单校验规则
const rules = reactive({
  couponName: [{ required: true, message: "优惠券名称不能为空", trigger: "blur" }],
  couponValue: [{ required: true, message: "优惠券金额不能为空", trigger: "blur" }],
  couponFeeOwner_0: [{ required: true, message: "费用承担方不能为空", trigger: "blur" }],
  couponFeeOwner_1: [{ required: true, message: "承担金额不能为空", trigger: "blur" }],
  amountPerUser: [{ required: true, message: "领取限量不能为空", trigger: "blur" }],
});


/* ---------------------------methods--------------------------- */

// 初始化数据
function initDataObj() {
  let coupon = props.formConfig.dataObj;
  Object.keys(coupon).forEach(key => {
    dataObj[key] = coupon[key]
  })
  console.log(dataObj, props.formConfig.dataObj)
  dataObj.couponValue = dataObj.couponValue / 100;
  dataObj.expiredAt = new Date(dataObj.expiredAt);
  dataObj.couponFeeOwner_0 = dataObj.couponFeeOwner[0];
  dataObj.couponFeeOwner_1 = dataObj.couponFeeOwner[1] / 100;

  // 区域
  if (Array.isArray(dataObj.regionIds) && dataObj.regionIds[0] == '*') {
    dataObj.regionIds_list = store.state.areaOption.map(val => val.id);
  } else {
    dataObj.regionIds_list = dataObj.regionIds
  }

  // 站点
  if (Array.isArray(dataObj.siteIds) && dataObj.siteIds[0] == '*') {
    dataObj.siteIds_list = props.allSiteList.map(val => val.siteId);
  } else {
    dataObj.siteIds_list = dataObj.siteIds
  }

  // 店铺
  dataObj.storeListStr = props.idsToNamesForAll('store', dataObj.storeIds)
  dataObj.storeIds_list = [...dataObj.storeIds]

}


// 点击选择店铺
function clickChooseStore() {
  addStoreDialog.show = true;
}
// 更新店铺
function updateStoreOkFun(obj) {
  if (obj.datas.length == obj.dataSourceLength) {
    // 是全选
    dataObj.storeListStr = '全部'
    dataObj.storeIds_list = ['*']
  } else {
    dataObj.storeListStr = obj.names.join('，')
    dataObj.storeIds_list = obj.ids
  }
}

// 点击确定，提交数据
function clickSubmit() {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      submitForm();
    } else {
      console.log('提交校验不通过', fields)
    }
  })

}

// 提交新增 或编辑
function submitForm() {
  let params = getSubmitParam();
  if (!params) {
    return;
  }
  proxy.$http.post('/jx/jxMarketing/createOrUpdateCoupon', params, { successTip: true }).then(res => {
    if (res.code == 200) {
      props.formConfig.dialog.show = false;
      props.formConfig.okCallback();
    }
  })
}


// 获取要保存的数据
function getSubmitParam() {
  let regionIds_list = [...dataObj.regionIds_list]
  if (regionIds_list.length == store.state.areaOption.length) {
    regionIds_list = ['*']
  }
  let siteIds_list = [...dataObj.siteIds_list]
  if (siteIds_list.length == props.allSiteList.length) {
    siteIds_list = ['*']
  }

  let params = {
    couponName: dataObj.couponName,
    couponValue: dataObj.couponValue * 100,
    amountPerUser: dataObj.amountPerUser,     //  每个用户可以领取几张，比如，新手大礼包，用户可以领取多张 1元或2元券；其他券，通常情况下，每个用户每天只能领取一张
    expiredAt: new Date(dataObj.expiredAt).getTime(), //  有效期截止时间
    regionIds: regionIds_list,                        //  * 号表示所有区域，多个区域id之间使用逗号分隔
    siteIds: siteIds_list,                            //  * 号表示所有站点，多个站点id之间使用逗号分隔
    storeIds: dataObj.storeIds_list,                  //  * 号表示所有店铺，多个店铺id之间使用逗号分隔
    couponFeeOwner: [dataObj.couponFeeOwner_0, dataObj.couponFeeOwner_1 * 100],   //  有谁来承担优惠券对应的费用，以及承担金额 ["platform": 150]，金额单位为分，当前取值只有2个，platform 和 merchant
  }

  if (dataObj.couponId) {
    params.couponId = dataObj.couponId    // 说明是编辑
  }
  console.log(params)
  return params
}

// 点击取消的回调
function clickCancle() {
  props.formConfig.dialog.show = false;
}

// 对外暴露数据
defineExpose({});
</script>

<style lang="scss" scoped></style>
